package org.jeecg.tender.information.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.security.SecurityUtil;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.readExcel.entity.TenderInformationKeywordManagementRelEntity;
import org.jeecg.readExcel.service.TenderInformationKeywordManagementRelService;
import org.jeecg.tender.constant.PublishTypeEnum;
import org.jeecg.tender.information.entity.TenderInformation;
import org.jeecg.tender.information.mapper.TenderInformationMapper;
import org.jeecg.tender.information.service.ITenderInformationService;
import org.jeecg.tender.information.vo.TenderInformationDetailVO;
import org.jeecg.tender.information.vo.TenderInformationVO;
import org.jeecg.tender.keyword.entity.TenderSecurityKeywordManagement;
import org.jeecg.tender.keyword.service.ITenderSecurityKeywordManagementService;
import org.jeecg.tender.project.dto.req.SendProjectNoticeReqDto;
import org.jeecg.tender.project.dto.util.SendProjectNoticeUtil;
import org.jeecg.tender.taskJob.b2b10086.support.B2b10086PublishPageReq;
import org.jeecg.tender.taskJob.bdebid.support.BdebidRespInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: tender_information
 * @Author: jeecg-boot
 * @Date:   2025-02-24
 * @Version: V1.0
 */
@Slf4j
@Service
public class TenderInformationServiceImpl extends ServiceImpl<TenderInformationMapper, TenderInformation> implements ITenderInformationService {

    @Resource
    private ITenderSecurityKeywordManagementService tenderSecurityKeywordManagementService;
    @Resource
    private TenderInformationKeywordManagementRelService tenderInformationKeywordManagementRelService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Override
    public List<TenderInformationVO> queryPageInformationList(Page<TenderInformationVO> page, QueryWrapper<TenderInformation> queryWrapper) {
        String userId = SecurityUtil.getUserId();
        List<DepartIdModel> departIdModels = sysUserDepartService.queryDepartIdsOfUser(userId);
        if(CollectionUtils.isEmpty(departIdModels)){
            return null;
        }
        List<String> departIds = departIdModels.stream().map(DepartIdModel::getKey).collect(Collectors.toList());
        queryWrapper.getEntity().setKeywordManagementIds(departIds);

        List<TenderInformationVO> pageList=this.baseMapper.queryPageInformationList(page, queryWrapper);
        return pageList;
    }

    @Override
    public void saveB2b10086(String websiteName, String detail, String detailType, List<Long> lableList,
                             B2b10086PublishPageReq b10086PublishPageReq, List<SendProjectNoticeReqDto> noticeInfoList, String url,String publishType) {
        if (ObjectUtils.isNotEmpty(lableList)) {
            TenderInformation entity = new TenderInformation();
            entity.setStartTime(DateUtils.parseDatetime(b10086PublishPageReq.getPublishDate()));
            entity.setEndTime(DateUtils.parseDatetime(b10086PublishPageReq.getTenderSaleDeadline()));
            entity.setTenderDate(entity.getStartTime());
            entity.setTenderTitle(b10086PublishPageReq.getName());
            entity.setTenderDesc(detail);
            entity.setTenderDescType(detailType);
            entity.setTenderType("--");
            entity.setWebsiteName(websiteName);
            entity.setCrawlTime(new Date());
            entity.setCreateBy("system");
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setWebsiteUrl(url);
            entity.setPublishType(publishType);
            super.save(entity);

            // 保存标签
            List<TenderInformationKeywordManagementRelEntity> realList = lableList.stream().map(labelId -> {
                TenderInformationKeywordManagementRelEntity relEntity = new TenderInformationKeywordManagementRelEntity();
                relEntity.setInformation_id(String.valueOf(entity.getId()));
                relEntity.setSecurity_keyword_management_id(String.valueOf(labelId));
                relEntity.setCreate_by("system");
                relEntity.setCreate_time(new Date());
                relEntity.setUpdate_time(new Date());
                SendProjectNoticeReqDto sendProjectNoticeReqDto = SendProjectNoticeUtil.buildSendProjectNoticeReqDto(labelId, entity);
                TenderSecurityKeywordManagement byId = tenderSecurityKeywordManagementService.getById(labelId);
                String keywordName = ObjectUtils.isNotEmpty(byId) ? byId.getKeywordName() : "";
                sendProjectNoticeReqDto.setKeywordName(keywordName);
                sendProjectNoticeReqDto.setAddress(url);
                noticeInfoList.add(sendProjectNoticeReqDto);
                return relEntity;
            }).collect(Collectors.toList());
            tenderInformationKeywordManagementRelService.saveBatch(realList);
        }
    }

    @Override
    public void saveBdebid(String websiteName, String detail, String detailType, List<Long> lableList, BdebidRespInfo respInfo, List<SendProjectNoticeReqDto> noticeInfoList, String detailUrl) {
        if (ObjectUtils.isNotEmpty(lableList)) {
            TenderInformation entity = new TenderInformation();
            entity.setStartTime(DateUtils.parseDate(respInfo.getInfodate(), DateUtils.DATE_PATTERN));
            entity.setTenderDate(entity.getStartTime());
            entity.setTenderTitle(respInfo.getTitle());
            entity.setTenderDesc(detail);
            entity.setTenderDescType(detailType);
            entity.setTenderType("--");
            entity.setWebsiteName(websiteName);
            entity.setCrawlTime(new Date());
            entity.setCreateBy("system");
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            super.save(entity);
            // 保存标签
            List<TenderInformationKeywordManagementRelEntity> realList = lableList.stream().map(lableId -> {
                TenderInformationKeywordManagementRelEntity relEntity = new TenderInformationKeywordManagementRelEntity();
                relEntity.setInformation_id(String.valueOf(entity.getId()));
                relEntity.setSecurity_keyword_management_id(String.valueOf(lableId));
                relEntity.setCreate_by("system");
                relEntity.setCreate_time(new Date());
                relEntity.setUpdate_time(new Date());
                SendProjectNoticeReqDto sendProjectNoticeReqDto = SendProjectNoticeUtil.buildSendProjectNoticeReqDto(lableId, entity);
                sendProjectNoticeReqDto.setAddress(detailUrl);
                TenderSecurityKeywordManagement byId = tenderSecurityKeywordManagementService.getById(lableId);
                String keywordName = ObjectUtils.isNotEmpty(byId) ? byId.getKeywordName() : "";
                sendProjectNoticeReqDto.setKeywordName(keywordName);
                noticeInfoList.add(sendProjectNoticeReqDto);
                return relEntity;
            }).collect(Collectors.toList());
            tenderInformationKeywordManagementRelService.saveBatch(realList);
        }
    }

    @Override
    public void saveCg11185(List<Long> lableList, TenderInformation information, List<SendProjectNoticeReqDto> noticeInfoList, String href) {
        if (ObjectUtils.isNotEmpty(lableList)) {
            super.save(information);
            // 保存标签
            List<TenderInformationKeywordManagementRelEntity> realList = lableList.stream().map(lableId -> {
                TenderInformationKeywordManagementRelEntity relEntity = new TenderInformationKeywordManagementRelEntity();
                relEntity.setInformation_id(String.valueOf(information.getId()));
                relEntity.setSecurity_keyword_management_id(String.valueOf(lableId));
                relEntity.setCreate_by("system");
                relEntity.setCreate_time(new Date());
                relEntity.setUpdate_time(new Date());
                SendProjectNoticeReqDto sendProjectNoticeReqDto = SendProjectNoticeUtil.buildSendProjectNoticeReqDto(lableId, information);
                sendProjectNoticeReqDto.setAddress(href);
                TenderSecurityKeywordManagement byId = tenderSecurityKeywordManagementService.getById(lableId);
                String keywordName = ObjectUtils.isNotEmpty(byId) ? byId.getKeywordName() : "";
                sendProjectNoticeReqDto.setKeywordName(keywordName);
                noticeInfoList.add(sendProjectNoticeReqDto);
                return relEntity;
            }).collect(Collectors.toList());
            tenderInformationKeywordManagementRelService.saveBatch(realList);
        }
    }

    @Override
    public List<Long> checkLabel(String title) {
        Map<Long, String> securityMap = tenderSecurityKeywordManagementService.getCacheSecurityKeywordManagement();
        return securityMap.entrySet().stream()
                .filter(entry -> title.contains(entry.getValue())).map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    @Override
    public TenderInformationDetailVO queryDetailById(String id) {
        TenderInformation tenderInformation = this.lambdaQuery().eq(TenderInformation::getId, id).one();
        if (ObjectUtils.isNotEmpty(tenderInformation)) {
            TenderInformationDetailVO tenderInformationDetailVO = new TenderInformationDetailVO();
            tenderInformationDetailVO.setId(String.valueOf(tenderInformation.getId()));
            tenderInformationDetailVO.setTenderTitle(tenderInformation.getTenderTitle());
            tenderInformationDetailVO.setTenderDescType(tenderInformation.getTenderDescType());
            if(("image").equals(tenderInformation.getTenderDescType())){
                List<String> images = Arrays.asList(tenderInformation.getTenderDesc().split(","));
                tenderInformationDetailVO.setTenderDescList(images);
            }else{
                tenderInformationDetailVO.setTenderDesc(tenderInformation.getTenderDesc());
            }
            return tenderInformationDetailVO;
        }

        return null;
    }

    @Override
    public List<TenderInformation> getTenderInformationWebsite(Date startTime, Date endTime) {
        return baseMapper.getTenderInformationWebsite(startTime, endTime);
    }


}
